package com.duowei.kitchenshow.fragment;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.android.volley.VolleyError;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.duowei.kitchenshow.MainActivity;
import com.duowei.kitchenshow.R;
import com.duowei.kitchenshow.adapter.RvRightAdapter;
import com.duowei.kitchenshow.adapter.SpacesItemDecoration;
import com.duowei.kitchenshow.app.MyApp;
import com.duowei.kitchenshow.bean.Cfpb_item;
import com.duowei.kitchenshow.event.HttpResponse;
import com.duowei.kitchenshow.event.ShowLoad;
import com.duowei.kitchenshow.event.ShowOut;
import com.duowei.kitchenshow.httputils.DownHTTP;
import com.duowei.kitchenshow.httputils.Post;
import com.duowei.kitchenshow.httputils.VolleyResultListener;
import com.duowei.kitchenshow.print.PrintNet;
import com.duowei.kitchenshow.service.Net;
import com.duowei.kitchenshow.utils.DateTimes;
import com.duowei.kitchenshow.utils.SpUtils;
import com.duowei.kitchenshow.utils.ToastUtil;
import com.google.gson.JsonSyntaxException;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechSynthesizer;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
public class OutFragment extends Fragment implements View.OnClickListener,
        BaseQuickAdapter.OnRecyclerViewItemClickListener {
    private RvRightAdapter mRvRightAdapter;
    private String mPrintIp;
    private String mCall;
    private static SpeechSynthesizer mTts;
    private String mCallStyle;

    public OutFragment() {
        // Required empty public constructor
    }
    private List<Cfpb_item> mCfpbItemList=new ArrayList<>();
    private List<Cfpb_item> tempList=new ArrayList<>();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View inflate = inflater.inflate(R.layout.fragment_out, container, false);
        EventBus.getDefault().register(this);

        mPrintIp = (String) SpUtils.get(getString(R.string.pringIp), "");
        mCallStyle = (String) SpUtils.get(getString(R.string.callStyle), "padCall");
        if("padCall".equals(mCallStyle)){
            setPadCall();
        }

        inflate.findViewById(R.id.btn_confirm).setOnClickListener(this);
        inflate.findViewById(R.id.btn_cancel).setOnClickListener(this);
        RecyclerView rvOut = inflate.findViewById(R.id.rv_out);
        rvOut.setLayoutManager(new LinearLayoutManager(getActivity()));
        rvOut.addItemDecoration(new SpacesItemDecoration(3));
        mRvRightAdapter = new RvRightAdapter(R.layout.out_item,mCfpbItemList);
        rvOut.setAdapter(mRvRightAdapter);
        mRvRightAdapter.setOnRecyclerViewItemClickListener(this);
        return inflate;
    }

    private void setPadCall() {
        mTts= SpeechSynthesizer.createSynthesizer(MyApp.getContext(), null);
        //设置合成语速
        mTts.setParameter(SpeechConstant.SPEED, "60");
        //设置合成音调
        mTts.setParameter(SpeechConstant.PITCH, "50");
        //设置合成音量
        mTts.setParameter(SpeechConstant.VOLUME, "100");

        mCall = (String) SpUtils.get(getString(R.string.callMessage), "*号，*号，丝恋喊你过来取餐啦！");
        String voiceName = (String) SpUtils.get(getString(R.string.voiceName), "xiaoyan");
        mTts.setParameter(SpeechConstant.VOICE_NAME, voiceName);
    }

    @Subscribe
    public void showOut(ShowOut event){
        mCfpbItemList = event.getCfpbItem();
        mRvRightAdapter.setNewData(mCfpbItemList);
    }

    @Override
    public void onClick(View v) {
        if(v.getId()==R.id.btn_cancel){
            Post.getInstance().postUpdate(0, MainActivity.showTable);
        }else if(v.getId()==R.id.btn_confirm){
            EventBus.getDefault().post(new ShowLoad(true));
            String sql_Ins_Del="";
            String tableNo="";
            for(int i=0;i<mCfpbItemList.size();i++){
                Cfpb_item cfpbItem = mCfpbItemList.get(i);
                sql_Ins_Del+="insert into CFPBYWC (XH, MTXH, WMDBH, XMBH, XMMC, DW, SL, PZ, XSZT, YHMC, POS, TDSL, XDSJ, WCSJ,      BY1, BY2, BY3, BY4, BY5, BY6, BY7) " +
                        "             select XH, MTXH, WMDBH, XMBH, XMMC, DW, SL, PZ, XSZT, YHMC, POS, TDSL, XDSJ, GETDATE(), BY1, BY2, BY3, BY4, BY5, BY6, BY7 " +
                        "             from CFPB where xh = '" + cfpbItem.xh + "'"+
                        " delete from cfpb where xh='"+cfpbItem.xh+"'";

                if("tvCall".equals(mCallStyle)){//电视呼叫
                    String czmc = getCzmc(cfpbItem);
                    if(!tableNo.equals(czmc)){
                        sql_Ins_Del+="delete from kdscall where TableNo='"+czmc+"'";
                        tableNo=czmc;
                    }
                }
            }
            final String sql="begin "+sql_Ins_Del+"end "+ BaseMainFragment.sql;
            DownHTTP.postVolley6(Net.url, sql, new VolleyResultListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    ToastUtil.showToast(error+"");
                }

                @Override
                public void onResponse(String response) {
                    try{
                        tempList.clear();
                        tempList.addAll(mCfpbItemList);
                        if(!TextUtils.isEmpty(mPrintIp)){
                            PrintNet.getInstance().startPrint(mPrintIp,tempList);
                        }
                        for(int i=0;i<mCfpbItemList.size();i++){
                            mCfpbItemList.get(i).setWcsj(DateTimes.getSysTime());
                        }
                        DataSupport.saveAll(mCfpbItemList);
                        EventBus.getDefault().post(new HttpResponse(response,true));
                    }catch (JsonSyntaxException e){
                        ToastUtil.showToast(response);
                    }
                }
            });
        }
    }

    @Override public void onItemClick(View view, int i) {
        Cfpb_item cfpb_item = mCfpbItemList.get(i);
        String czmc = getCzmc(cfpb_item);
        if("padCall".equals(mCallStyle)){//平板呼叫
            if(mCall.contains("*")){
                String msg = mCall.replace("*", czmc);
                mTts.startSpeaking(msg, null);
            }else{
                ToastUtil.showToast("请设置*号代替桌号");
            }
        }else{//电视呼叫
            String sql="update kdscall set yhj = '1', xdsj = getdate() where TableNo = '" + czmc + "'|";
            Post.getInstance().postCall(sql,true);
        }
    }

    @NonNull
    private String getCzmc(Cfpb_item cfpb_item) {
        String czmc;
        if(cfpb_item.czmc1.contains(",")){
            czmc = cfpb_item.czmc1.replace(",", "");
        }else{
            czmc=cfpb_item.czmc1;
        }
        return czmc;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
